﻿using System;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 封装一层
/// </summary>
public class KeyInfo
{
    public List<KeyCode> keys = new List<KeyCode>();
    public string keyNames;
    public KeyInfo(List<KeyCode> keys)
    {
        this.keys = keys;
        for (int i = 0; i < keys.Count; i++)
        {
            keyNames += keys[i].ToString();
            if (i < keys.Count - 1)
                keyNames += " --> ";
        }
    }

    public int triggerIndex = -1;
    public bool trigger(KeyCode key)
    {
        KeyCode nowKey = keys[triggerIndex + 1];
        if (nowKey == key)
        {
            triggerIndex++;
        }
        else
        {
            triggerIndex = -1;
        }
        return triggerIndex >= keys.Count - 1;
    }

    public void reset() {
        triggerIndex = -1;
    }
}

/// <summary>
/// 输入触发器
/// </summary>
public class InputTriggerMgr : Singleton<InputTriggerMgr>
{
    private Dictionary<string, KeyInfo> triggerMap = null;
    private double lastTime = -1;
    protected int interval =500;

    protected override void initialize()
    {
        triggerMap = new Dictionary<string, KeyInfo>();
        lastTime = TimerUtils.getMillTimer();
    }

    //添加一个触发
    public void addTrigger(string name, KeyInfo info)
    {
        if (triggerMap.ContainsKey(name))
        {
            triggerMap[name] = info;
        }
        else
        {
            triggerMap.Add(name, info);
        }
    }
    //移除一个触发
    public void removeTrigger(string name)
    {
        if (triggerMap.ContainsKey(name))
        {
            triggerMap.Remove(name);
        }
    }

    public void onKeyDown(KeyCode key)
    {
        double nowTime = TimerUtils.getMillTimer();
        bool isReset = nowTime - lastTime > interval;
        lastTime = nowTime;

        foreach (var item in triggerMap)
        {
            string keyName = item.Key;
            if (isReset) {
                item.Value.reset();
            }
            bool isFinish = item.Value.trigger(key);
            if (isFinish)
            {
                item.Value.reset();
                Debug.LogError(item.Key + " : " + item.Value.keyNames);
            }
        }
    }

}

